// utils/kimiyuans.ts

interface Choice {
    delta: {
      content?: string;
      role?: string;
    };
    usage?: {
      total_tokens: number;
    };
  }
  
  interface AIResponse {
    choices: Choice[];
  }
  
  export async function getAIResponse(messages: { role: string; content: string }[]): Promise<string | undefined> {
    const data = {
      model: "moonshot-v1-128k",
      messages,
      temperature: 0.3,
      stream: true,
    };
  
    try {
      const response = await fetch("https://api.moonshot.cn/v1/chat/completions", {
        method: "POST",
        headers: {
          'Authorization': `Bearer ${import.meta.env.VITE_KIMI_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });
  
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
  
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('Failed to get reader from response');
      }
  
      const decoder = new TextDecoder();
      let buffer = "";
      let finalResponse = ""; // 用于存储最终的 AI 响应
  
      const processStream = async (): Promise<void> => {
        const { done, value } = await reader.read(); // 读取数据块
        if (done) {
          console.log("Stream finished");
          return;
        }
  
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || ""; // 处理剩余部分
  
        for (const line of lines) {
          if (line.startsWith("data: ")) {
            const jsonString = line.substring(6).trim(); // 去除 "data: " 前缀
  
            if (jsonString === "[DONE]") {
              return; // 结束流处理
            }
  
            try {
              const json: AIResponse = JSON.parse(jsonString);
              const content = json.choices[0]?.delta?.content;
              if (content) {
                finalResponse += content; // 累加内容
              }
            } catch (e) {
              console.error("Error parsing JSON:", e);
            }
          }
        }
  
        await processStream(); // 递归调用
      };
  
      await processStream(); // 启动流式处理
  
      // 返回最终的 AI 响应
      return finalResponse || undefined;
    } catch (error) {
      console.error("Error fetching AI response:", error);
      throw error; // 传递错误，确保调用者知道发生了错误
    }
  }
  